package org.HisCanvas.ChrisRiffle.JFlightLog.swingUi.common;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import org.HisCanvas.ChrisRiffle.JFlightLog.dataModel.LogBookRec;
import org.HisCanvas.ChrisRiffle.JFlightLog.launching.JFlightLogController;
import org.HisCanvas.ChrisRiffle.JFlightLog.logging.LogController;
import org.HisCanvas.ChrisRiffle.JFlightLog.swingUi.mainTopFrame.FlightLogMainFrameController;
import org.HisCanvas.ChrisRiffle.JFlightLog.swingUi.recordDetailWindow.LogBookRecDialog;
import org.HisCanvas.ChrisRiffle.JFlightLog.swingUi.recordDetailWindow.LogBookRecDialogController;
import org.HisCanvas.ChrisRiffle.JFlightLog.swingUi.table.FlightLogTableController;

public class UserCommandListener implements ActionListener {

	private static UserCommandListener INSTANCE;

	public static final String ADD_FLIGHT_RECORD = "ADD_FLIGHT_CLICK";

	public static final String EDIT_FLIGHT_RECORD = "EDIT_FLIGHT_CLICK";

	public static final String DELETE_FLIGHT_RECORD = "DELETE_FLIGHT_CLICK";

	private UserCommandListener() {
	}

	public static UserCommandListener instance() {

		if (INSTANCE == null) {
			INSTANCE = new UserCommandListener();
		}
		return INSTANCE;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		String userCommand = e.getActionCommand();

		if (ADD_FLIGHT_RECORD.equals(userCommand)) {

			handleAddFlight();

		} else if (EDIT_FLIGHT_RECORD.equals(userCommand)) {

			handleEditFlight();

		} else if (DELETE_FLIGHT_RECORD.equals(userCommand)) {

			handleDeleteFlight();
		}

	}

	private void handleEditFlight() {

		LogBookRec selectedRec = FlightLogTableController.instance()
				.getSelectedFlight();

		LogBookRecDialogController.instance().displayEditFlightDialog(
				selectedRec);
	}

	private void handleAddFlight() {

		LogBookRecDialogController.instance().displayAddFlightDialog();
	}

	
	/**
	 * handles user's delete record action
	 */
	private void handleDeleteFlight() {

		LogBookRec selectedFlight = FlightLogTableController.instance()
				.getSelectedFlight();

		
		int usersDeleteConfirmation = JOptionPane.showConfirmDialog(
				LogBookRecDialogController.instance().getLogBookRecDialog(), "Delete Record?");
		
		if(usersDeleteConfirmation != JOptionPane.YES_OPTION){
			//user backed out of deletion so exit the process
			return;
		}
		
		try {

			JFlightLogController.instance().getLogBookDao()
					.removeLogBookRec(selectedFlight);
			
			FlightLogTableController.instance().refreshTableView();

		} catch (Exception e) {

			LogController.severe("Unable to remove flight with key: "
					+ selectedFlight.getPrimaryKey());
			e.printStackTrace();
		}

	}

}
